﻿using System;

namespace N2.Web
{
	using N2.Configuration;
	
	public sealed class JsonRequestAdapter : RequestAdapter
	{
		public override void RewriteRequest(RewriteMethod rewriteMethod)
		{
			if (Path != null && !Path.IsEmpty()) {
				var _ctx = Engine.Resolve<IWebContext>();
				var _req = _ctx.Request;

				//How Astoria recognizes that JSON was requested:
				//http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataservices/thread/4a652e0e-5a9f-44e2-bf35-301cefd1afa4/
				
				//var webContext = Path.QueryParameters

				var _jsonRequested =
					string.Equals(
						_req.QueryString["$format"],
						"json",
						StringComparison.OrdinalIgnoreCase)
					
					|| Array.Exists(
						_req.AcceptTypes,
						_s => string.Equals(
							_s,
							"application/json",
							StringComparison.OrdinalIgnoreCase));

				if (_jsonRequested) {
					_ctx.RewritePath("~/Json.axd?id=" + Path.ID.ToString());
					return;
				}
			}
			
			base.RewriteRequest(rewriteMethod);
		}
	}
}
